import router from "@/router"
import { useLoginUserStore } from "@/stores/loginUser"
import ACCESS_ENUM from "./accessEnum"
import checkAccess from "./checkAccess"

/**
 * 全局权限校验
 */
router.beforeEach(async (to, from, next) => {
  const loginUserStore = useLoginUserStore()
  let loginUser = loginUserStore.loginUser

  if (!loginUser || !loginUser.userRole) {
    await loginUserStore.fetchLoginUser()
    loginUser = loginUserStore.loginUser
  }

  const needAccess = (to.meta.access as string) ?? ACCESS_ENUM.NOT_LOGIN

  // 必须要登录才能访问
  if (needAccess !== ACCESS_ENUM.NOT_LOGIN) {
    if (!loginUser || !loginUser.userRole || loginUser.userRole === ACCESS_ENUM.NOT_LOGIN) {
      next(`/user/login?redirect=${to.fullPath}`)
      return
    }

    // 如果已经登录，判断是否具有访问权限
    if (!checkAccess(loginUser, needAccess)) {
      next("/no-auth")
      return
    }
  }

  next()
})
